<?php

	class Session
	{
		public $db;		                              // Datasources
	
		public $cookie_name = SESSION_COOKIE_NAME;    // name of the cookie to store the $session_id

		public $user_id;                              // Authenticated User
		public $session_id;                           // uuid
		public $start_time;                           // session start
		public $expire_time;                          // session start
		public $expires = '1800';                     // 30 Min (in seconds)
		public $user_agent;                           // users browser identification
		public $ip_address;                           // user ip address
		public $referrer_domain;                      // referring page (original to the website)
		public $referrer_full;                        // referring page (original to the website)
		public $referrer_keyword;                     // keyword that lead to visit site
		public $page_views = 0;                       // number of pages viewed during this session
		
		private $lookup_results;                      // the stored result of the lookup (now we don't need to query for it again!)

		#
		#	Public Functions
		#

		public function __construct()
		{	
			global $_DATASOURCE;
			$this->db = $_DATASOURCE;
			
			$this->init();
		}

		public function init()
		{
			$this->start_time = date('U');
			$this->expires_time = ($this->start_time + $this->expires);
			$this->user_agent = $_SERVER['HTTP_USER_AGENT'];
			$this->ip_address = $_SERVER['REMOTE_ADDR'];
			$this->referrer_domain = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
			$this->referrer_full = $_SERVER['HTTP_REFERER'];
			$this->keyword = $this->keyword_discover();
		
			$this->start();
		}
		
		public function start()
		{
			if( isset($_COOKIE[$this->cookie_name]) )
			{
				$this->session_id = $_COOKIE[$this->cookie_name];
			}
			
			$exists = $this->lookup( $this->session_id );
			if($exists)
			{
				session_name($this->cookie_name);
				session_start();
				$this->update( );
			}
			else
			{
				session_name($this->cookie_name);
				session_start();
				$this->create( );
			}		
		}	
		
		public function end()
		{
			# get a new session id, and lose the old one. We HAVE to have a session!
			session_regenerate_id(true);
			setcookie( $this->cookie_name, session_id(), 0, '/' );
		}
		
		public function authorize($user_id)
		{
			$this->user_id = $user_id;
			$this->update();
			return;
		}

		public function deauthorize()
		{
			$this->user_id = 0;
			$this->end();
			$this->init();
			return;
		}
	
		#
		#	Private Functions
		#
		
		private function lookup( $this_session_id = '0' )
		{
			$this->cleanup();
			$this->lookup_results = $this->db->default->select("select * from sessions where session_id = '{$this->session_id}'");
			if( count($this->lookup_results) > 0 )
			{
				return true;
			}
			return false;
		}

		private function update()
		{
			foreach($this->lookup_results[0] as $key => $value)
			{
				$this->$key = $value;
			}
			$this->expires_time = (date('U') + $this->expires);
			$this->page_views++;		
			
			$sql  = "
				update sessions
				set
					user_id = {$this->user_id}, 
					start_time = {$this->start_time}, 
					expire_time = {$this->expires_time}, 
					page_views = {$this->page_views}
				where 
					session_id = '{$this->session_id}'
				";
				
			$tmp = $this->db->default->update($sql);
			
		}
		
		private function create()
		{
			$this->session_id = session_id();
			
			if( empty($this->session_id) )
			{
				return;
			}
			
			$this->user_id = 0;
			$this->page_views = 1;

			$sql  = "
				insert into sessions
				(
					session_id, 
					user_id, 
					start_time, 
					expire_time, 
					user_agent, 
					ip_address, 
					referrer_domain, 
					referrer_full, 
					referrer_keyword, 
					page_views
				)
				values
				(
					'{$this->session_id}', 
					{$this->user_id}, 
					{$this->start_time}, 
					{$this->expires_time}, 
					'{$this->user_agent}', 
					'{$this->ip_address}', 
					'{$this->referrer_domain}', 
					'{$this->referrer_full}', 
					'{$this->keyword}', 
					{$this->page_views}
				)
			";
			
			$tmp = $this->db->default->insert($sql);
				
		}

		private function keyword_discover()
		{
			$qstring = parse_url($this->referrer_full, PHP_URL_QUERY);
					
			if($qstring == false)
			{
				return false;
			}
				
			parse_str($qstring, $urlvars);
						
			//-- discover keywords ------------------------------

			if(isset($urlvars['p'])){ $keywords = $urlvars['p']; }									//Yahoo!
			else if(isset($urlvars['q'])){ $keywords = $urlvars['q']; }								//Google or Ask or IMDB or MSN or Alexa or Live.com or Cuil
			else if(isset($urlvars['searchfor'])){ $keywords = $urlvars['searchfor']; }				//MyWay
			else if(isset($urlvars['field-keywords'])){ $keywords = $urlvars['field-keywords']; }	//Amazon
			else if(isset($urlvars['form_keyword'])){ $keywords = $urlvars['form_keyword']; }		//PriceGrabber
			else if(isset($urlvars['qry'])){ $keywords = $urlvars['qry']; }							//MySpace
			else if(isset($urlvars['nm'])){ $keywords = $urlvars['nm']; }							//Facebook
			else if(isset($urlvars['query'])){ $keywords = $urlvars['query']; }						//Lycos or AOL or Craigslist or Misc
			else if(isset($urlvars['wd'])){ $keywords = $urlvars['wd']; }							//baidu		

			return $keywords;
		}
		
		private function cleanup()
		{
			$this->db->default->delete('delete from sessions where expire_time < ' . (date('U') - $this->expires));
			return;
		}
	}

?>